<?php

namespace App\Models\back;

use App\Tool\Tool;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;


class Ajax extends Model
{
	/*
	 * js远程验证品牌名是否已存在
	 */
    public function brandValidator($request)
    {
	    if (isset($request['id'])) {
		    $id = $request['id'];
	    } else {
		    $id = 0;
	    }

	    $validator = Validator::make($request, [
		    'title' => [
			    Rule::unique('brands')->ignore($id),
		    ]
	    ]);

	    if ($validator->fails()) {
		    return false;
	    } else {
	    	return true;
	    }
    }

	/*
	 * js远程验证分类名是否已存在
	 */
	public function categoryValidator($request)
	{
		if (isset($request['id'])) {
			$id = $request['id'];
		} else {
			$id = 0;
		}

		$validator = Validator::make($request, [
			'title' => [
				Rule::unique('categories')->ignore($id),
			]
		]);

		if ($validator->fails()) {
			return false;
		} else {
			return true;
		}
	}

	/*
	 * js远程验证父分类是否是当前分类的子分类或者本分类
	 */
	public function categoryParentValidator($request)
	{
		if ($request['id'] == 0) {
			return true;
		} else {
			//获取分类列表集合
			$categoryList = DB::table('categories')->select('id', 'parent_id')->get();
			return Tool::checkChild($request['parent_id'], $request['id'], json_decode($categoryList, true));
		}
	}
}
